package com.bwie.handler;
import com.bwie.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.bwie.exception.LoginException;

import java.util.List;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    /**
     * 登录异常处理
     * @return
     */
    @ExceptionHandler(LoginException.class)
    public Result loginExceptionHandler(LoginException loginException) {

        log.error("登录模块异常，异常信息：{}", loginException.getMessage());
       return Result.error(loginException.getCode(), loginException.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result MethodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException){
        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
        //获取所有异常个信息
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();
        allErrors.forEach(error->{
            String defaultMessage = error.getDefaultMessage();
            stringBuilder.append(defaultMessage+"");
        });
        log.error(stringBuilder.toString());
        return Result.error(stringBuilder.toString());
    }

}
